package com.qzsoft.zhjd.machine.zhgcloud.realtime;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qzsoft.zhjd.machine.modules.machinefuel.entity.MachineFuelEntity;
import com.qzsoft.zhjd.machine.modules.machineinfo.entity.MachineInfoEntity;
import com.qzsoft.zhjd.machine.modules.machineinfo.service.MachineInfoService;
import com.qzsoft.zhjd.machine.modules.machinerealtime.entity.MachineRealtimeEntity;
import com.qzsoft.zhjd.machine.modules.machinerealtime.service.MachineRealtimeService;
import com.qzsoft.zhjd.machine.zhgcloud.ZhgHandler;
import com.qzsoft.zhjd.machine.zhgcloud.ZhgResultDataCallback;
import com.qzsoft.zhjd.machine.zhgcloud.fuel.ZhgFuelHandler;
import com.qzsoft.zhjd.machine.zhgcloud.realtime.model.ZhgRealtimeDataModel;
import com.qzsoft.zhjd.machine.zhgcloud.realtime.model.ZhgRealtimeDeviceModel;
import com.qzsoft.zhjd.machine.zhgcloud.realtime.model.ZhgRealtimeModel;

/**
 * @ClassName ZhgRealtimeHandler
 * @Description 指挥官系统获取实时数据
 * @author linhuawei
 * @since 2021-11-08
 */
@Component
public class ZhgRealtimeHandler {

    @Value("${zhgcloud.urls.realtime}")
    private String realtimeUrl;

    @Autowired
    private ZhgFuelHandler zhgFuelHandler;

    @Autowired
    private ZhgHandler zhgHandler;

    @Autowired
    private MachineRealtimeService machineRealtimeService;

    @Autowired
    private MachineInfoService machineInfoService;

    /**
     * @Title realtime
     * @Description 获取机械设备实时数据
     * @param machineKeyMap 设备编号主键映射
     */
    public void realtime() {
        // 获取数据列表
        List<ZhgRealtimeModel> realtimeList = getRealtimeList();
        if (ObjectUtils.isEmpty(realtimeList)) {
            return;
        }

        // 获取设备编号主键映射
        QueryWrapper<MachineInfoEntity> queryWrapper = new QueryWrapper<MachineInfoEntity>();
        queryWrapper.select("id", "machine_key");
        List<MachineInfoEntity> machineList = machineInfoService.list(queryWrapper);
        Map<String, String> machineKeyMap = new HashMap<String, String>();
        machineList.forEach(item -> {
            if (ObjectUtils.isNotEmpty(item.getMachineKey())) {
                machineKeyMap.put(item.getMachineKey(), item.getId());
            }
        });

        // 获取油位数据
        List<MachineFuelEntity> fuelList = zhgFuelHandler.fuel(machineKeyMap);
        Map<String, MachineFuelEntity> fuelMap = new HashMap<String, MachineFuelEntity>();
        if (ObjectUtils.isNotEmpty(fuelList)) {
            fuelList.forEach(item -> {
                fuelMap.put(item.getMachineKey(), item);
            });
        }

        // 数据转换
        MachineRealtimeEntity entity;
        ZhgRealtimeModel model;
        ZhgRealtimeDataModel dataModel;
        ZhgRealtimeDeviceModel deviceModel;
        MachineFuelEntity fuelEntity;
        String machineId;
        for (int i = 0, len = realtimeList.size(); i < len; i++) {
            // 获取设备主键
            model = realtimeList.get(i);
            machineId = machineKeyMap.get(model.getMachine_key());
            if (ObjectUtils.isEmpty(machineId)) {
                continue;
            }

            // 数据转化
            entity = new MachineRealtimeEntity();
            entity.setMachineId(machineId);
            entity.setMachineKey(model.getMachine_key());
            entity.setOnlineState(model.getOnline_state());
            dataModel = model.getData_real_time();
            if (null != dataModel) {
                entity.setState(dataModel.getState());
                entity.setDeviceState(dataModel.getDevice_state());
                entity.setStandingTime(dataModel.getStanding_time());
                entity.setStateUpdateTime(dataModel.getStateUpdateAt());
                entity.setAddress(dataModel.getAddress());
                entity.setLongitude(dataModel.getLongitude());
                entity.setLatitude(dataModel.getLatitude());
                entity.setLocationTime(dataModel.getLastLocationAt());

                deviceModel = dataModel.getDevice();
                if (null != deviceModel) {
                    entity.setDeviceTerminalSn(deviceModel.getTerminal_sn());
                    entity.setDeviceModel(deviceModel.getModel());
                    entity.setDeviceBatteryPercent(deviceModel.getBattery_percent());
                    entity.setDeviceBindTime(deviceModel.getBind_at());
                    entity.setDeviceOnlineTime(deviceModel.getOnline_at());
                }
            }

            // 油位信息
            fuelEntity = fuelMap.get(model.getMachine_key());
            if (null != fuelEntity) {
                entity.setFuelVolume(fuelEntity.getVolume());
                entity.setFuelPercentage(fuelEntity.getPercentage());
                entity.setFuelReportTime(fuelEntity.getReportDate());
            }
            machineRealtimeService.save(entity);
        }
    }

    /**
     * @Title getRealtimeList
     * @Description 获取实时数据列表
     * @return 实时数据列表
     */
    public List<ZhgRealtimeModel> getRealtimeList() {
        // 获取查询条件
        Map<String, Object> params = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        params.put("timestamp", sdf.format(new Date()));

        // 获取数据列表
        ZhgResultDataCallback callback = (JSONObject resultJson) -> {
            return null == resultJson.getJSONObject("result") ? null
                    : resultJson.getJSONObject("result").getString("data_list");
        };
        return zhgHandler.httpGetList(realtimeUrl, params, ZhgRealtimeModel.class, callback);
    }

}
